/*
 * @Author: lvjiaxuan
 * @Date: 2017-11-25 09:55:23
 * @Last Modified by: lvjiaxuan
 * @Last Modified time: 2017-12-25 17:15:35
 */

const express = require('express');
const Goods = require('./../models/Goods');
const Users = require('./../models/Users')
const router = express.Router();

let userInfo = {
	userId: '',
	userName: ''
};

let reData = (status = '', msg = '', result = '') => {
	return { status, msg, result }
};

router.use((req, res, next) => {

	// req.cookies = new Cookies(req, res);
	userInfo = req.cookies.get('userInfo') ? JSON.parse(req.cookies.get('userInfo')) : userInfo;
	next();
});

/** 首页：查询商品列表 */
router.get('/', (req, res) => {
	// let sort = req.param('sort');

	let reqQuery = req.query;
	let {sort, page, limit, priceLevel} = req.query;
	sort =  Number(sort) || 1;
	page = Number(page) || 1;
	limit = Number(limit) || 4;

	let params = {};
	let priceMax, priceMin;
	switch (priceLevel) {
		case '0': priceMin=0;priceMax=500;break;
		case '1': priceMin=500;priceMax=1000;break;
		case '2': priceMin=1000;priceMax=1500;break;
		case '3': priceMin=1500;priceMax=5000;break;
		default:priceMax='';priceMin='';
	};

	if(priceMax != priceMin) {
		params = {
			salePrice: {
				$gt: priceMin,
				$lte: priceMax
			}
		};
	}

	Goods.find(params).sort({'salePrice':sort}).skip((page - 1) * limit).limit(limit).exec((err, doc) => {
		if(err) {
			res.json({
				status:'1',
				msg: err.message
			});
		} else {
			res.json({
				status:'0',
				msg: '', //success
				result: {
					count: doc.length,
					list: doc
				}
			});
		}
	});
});

/** 加入购物车 */
router.post('/addCart', (req, res) => {

	let userId = userInfo.userId;
	let productId = req.body.productId;

	Users.findOne({ userId })
	.then(user => {
		if(user) {
			Goods.findOne({
				productId
			}).then(good => {
				if(good) {
					good.checked = 1;

					let _good = user.cartList.id(good._id)
					// 购物车已存在该good
					if(_good) {
						_good.productNum++;
					} else {
						good.productNum = 1;
						user.cartList.push(good);
					}

					user.save().then(() => {
						res.json({
							status: '0',
							msg: '', // success
							result: good
						});
					});
				} else {
					res.json({
						status: '1',
						msg: 'good不存在'
					});
				}
			});
		} else {
			res.json({
				status: '1',
				msg: 'user不存在'
			});
		}
	});
});

module.exports = router;